package com.chen.gui.border;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;

import javax.swing.JPanel;
import javax.swing.border.Border;

import com.chen.Shell;

/**
 * 
 * @author Chen
 *
 */
public class RectBorder implements Border {

	public static final int plain = 0;
	public static final int bold = 1;

	private int style = plain;

	private Insets insets;

	public RectBorder() {
		this(0, new Insets(1, 1, 1, 1));
	}

	public RectBorder(int style, Insets insets) {
		if (style == plain || style == bold)
			this.style = style;

		if (insets == null)
			insets = new Insets(1, 1, 1, 1);

		this.insets = insets;
	}

	@Override
	public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
		int w = width;
		int h = height;

		Graphics2D g2d = (Graphics2D) g.create();
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g2d.setColor(c.getBackground().darker());

		if (style == bold)
			g2d.setStroke(new BasicStroke(2f));

		if (insets.top > 0) {
			g2d.drawLine(1, 1, w - 2, 1);
			// if (isGradient)
			// g2d.drawLine(1, 2, w - 2, 2);
		}

		if (insets.left > 0) {
			g2d.drawLine(1, 1, 1, h - 2);
			// if (isGradient)
			// g2d.drawLine(2, 1, 2, h - 2);
		}

		if (insets.bottom > 0) {
			g2d.drawLine(1, h - 2, w - 2, h - 2);
			// if (isGradient)
			// g2d.drawLine(1, h - 3, w - 2, h - 3);
		}

		if (insets.right > 0) {
			g2d.drawLine(w - 2, 1, w - 2, h - 2);
			// if (isGradient)
			// g2d.drawLine(w - 3, 1, w - 3, h - 2);
		}

		g2d.dispose();
	}

	@Override
	public Insets getBorderInsets(Component c) {
		return insets;
	}

	@Override
	public boolean isBorderOpaque() {
		return false;
	}

	public static void main(String[] args) {
		JPanel panel = new JPanel();
		panel.setBackground(Color.white);
		panel.setBorder(new RectBorder(plain, new Insets(2, 2, 2, 2)));
		Shell.run(panel);
	}
}
